<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >

      <el-row>
        <el-col>
          <el-form-item label="员工名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入员工名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-160px"
            />
          </el-form-item>
          <el-form-item label="审批状态" prop="checkState">
            <el-select
              v-model="queryParams.checkState"
              placeholder="请选择审批状态"
              clearable
              class="!w-160px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px"/>
              搜索
            </el-button>
          </el-form-item>

          <el-form-item>

            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px"/>
              重置
            </el-button>
<!--            <el-button-->
<!--              type="success"-->
<!--              plain-->
<!--              @click="handleExport"-->
<!--              :loading="exportLoading"-->
<!--              v-hasPermi="['app:users:export']"-->
<!--            >-->
<!--              <Icon icon="ep:download" class="mr-5px"/>-->
<!--              导出-->
<!--            </el-button>-->
          </el-form-item>

        </el-col>

      </el-row>


    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table border v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="编号" align="center" prop="id"/>-->
      <el-table-column label="员工名称" prop="name" min-width="200px"/>
      <el-table-column label="性别" align="center" prop="status">
        <template #default="scope">
          <dict-tag  style="color: black" :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mobile" min-width="200px"/>
      <el-table-column label="身份证号" align="center" prop="idCardNo" min-width="200px"/>
      <el-table-column label="身份证正面" align="center" prop="idCardFrontPic" min-width="200px">
        <template #default="scope">
          <el-image
            style="width: 20px; height: 20px"
            :src="scope.row.idCardFrontPic"
            :key="index"
            z-index="1000"
            :initial-index="index"
            hide-on-click-modal
            preview-teleported
            :preview-src-list="scope.row.idCardFrontPicList"
          />
        </template>
      </el-table-column>
      <el-table-column label="身份证反面" align="center" prop="idCardContraryPic" min-width="200px">
        <template #default="scope">
          <el-image
            style="width: 20px; height: 20px"
            :src="scope.row.idCardContraryPic"
            :key="index"
            z-index="1000"
            :initial-index="index"
            hide-on-click-modal
            preview-teleported
            :preview-src-list="scope.row.idCardContraryPicList"
          />
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="checkState" min-width="150">
        <template #default="scope">
          <div
            :class="['custom-select', { 'priorit1' : scope.row.checkState === 0 || scope.row.checkState === 3,
          'priorit2' : scope.row.checkState === 1 || scope.row.checkState === 4,
          'priorit3' : scope.row.checkState === 2 || scope.row.checkState === 5}]">
            <el-select style="text-align: center;"
                       @change="handleStaffCheckChange(scope.row)"
                       v-model="scope.row.checkState">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address" min-width="200px">
        <template #default="scope">
          <!--    归属省份+归属城市+归属区+名称       -->

          <!--          {{ scope.row.belongProvince }}{{ scope.row.belongCity }}{{ scope.row.belongDistrict }}-->
          <!--          名称在添加时 拼接保存省市区-->
          {{ scope.row.address }}
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="avatar" min-width="200px">
        <template #default="scope">
          <el-image
            style="width: 20px; height: 20px"
            :src="scope.row.avatar"
            :key="index"
            z-index="1000"
            :initial-index="index"
            hide-on-click-modal
            preview-teleported
            :preview-src-list="scope.row.avatarList"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>


      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" width="120px" align="center" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['app:users:update']"
          >
            编辑
          </el-button>
<!--          <el-button-->
<!--            link-->
<!--            type="danger"-->
<!--            @click="handleDelete(scope.row.id)"-->
<!--            v-hasPermi="['app:users:delete']"-->
<!--          >-->
<!--            删除-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CompanyForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {getStrDictOptions, getIntDictOptions, DICT_TYPE, getDictObj} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {StaffApi, StaffVO} from '@/api/app/staff'
import CompanyForm from './CompanyForm.vue'
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";

/** 派单系统 门店 列表 */
defineOptions({name: 'Company'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<StaffVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: null,
  password: null,
  name: null,
  nickname: null,
  remark: null,
  deptId: null,
  postIds: null,
  email: null,
  mobile: null,
  sex: null,
  avatar: null,
  status: null,
  loginIp: null,
  loginDate: null,
  createTime: [],
  commissionRate: null,
  wxOpenId: null,
  unionId: null,
  miniOpenId: null,
  grantType: null,
  checkState: null,
  checkDesc: null,
  grade: null,
  isActivate: null,
  merchantId: null,
  grantType: 3
})
const getUserTypeColor = (type: number) => {
  const dict = getDictObj(DICT_TYPE.SYSTEM_USER_SEX, type)
  switch (dict?.colorType) {
    case 'success':
      return '#67C23A'
    case 'info':
      return '#909399'
    case 'warning':
      return '#E6A23C'
    case 'danger':
      return '#F56C6C'
  }
  return '#409EFF'
}
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.grantType =3;
    const data = await StaffApi.getAppUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleStaffCheckChange = async (row) => {

  const staffCheckOptions = getIntDictOptions(DICT_TYPE.ERP_NO_REPEAL_CHECK_TYPE);

  for (const key in staffCheckOptions) {
    if (staffCheckOptions[key].value === row.checkState) {

      await ElMessageBox.confirm(
        '员工【' + row.name + '】审批状态是否修改为【' + staffCheckOptions[key].label + '】?',
        '审批状态确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await StaffApi.updateAppUserCheckState(row.id, row.checkState);
            ElMessage({
              type: 'success',
              message: '审批状态已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getList()
        })
    }
  }

}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StaffApi.deleteAppUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StaffApi.exportAppUser(queryParams)
    download.excel(data, '派单系统 门店.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
const route = useRoute();
onActivated(() => {
  //快捷添加
  let query = route.query;
  if (query.doType == 'handAdd') {
    formRef.value.open("create");
  }
  getList();
});

</script>
